package cn.yunlang.zhangZhongFei.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.yunlang.zhangZhongFei.entity.SysUser;
import cn.yunlang.zhangZhongFei.mapper.SysUserMapper;
import cn.yunlang.zhangZhongFei.service.SysUserService;
import cn.yunlang.zhangZhongFei.vo.response.R;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 系统管理员表 服务实现类
 *
 * @author ·
 * @since 2025-05-27 09:54:49
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService {

  public R<IPage<SysUser>> pageSysUser(Integer pageNo, Integer pageSize) {
    if (pageNo == null || pageSize == null) {
      return R.error(400, "分页参数不能为空");
    }
    LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(SysUser::getIsDelete, 0);
    IPage<SysUser> page = this.page(new Page<>(pageNo, pageSize), wrapper);
    return R.success(page);
  }

  public R<SysUser> getOne(Long sysUserId) {
    if (sysUserId == null) {
      return R.error(400, "ID不能为空");
    }
    SysUser sysUser = this.getById(sysUserId);
    if (sysUser == null) {
      return R.error(404, "未找到系统用户");
    }
    return R.success(sysUser);
  }

  public R<String> addSysUser(SysUser sysUser) {
    if (sysUser == null
        || !StringUtils.hasText(sysUser.getUsername())
        || !StringUtils.hasText(sysUser.getPassword())) {
      return R.error(400, "用户名和密码不能为空");
    }
    // 用户名查重
    LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(SysUser::getUsername, sysUser.getUsername());
    if (this.count(wrapper) > 0) {
      return R.error(400, "用户名已存在");
    }
    sysUser.setPassword(DigestUtil.md5Hex(sysUser.getPassword()));
    boolean save = this.save(sysUser);
    return save ? R.success("新增成功") : R.error(500, "新增失败");
  }

  public R<String> deleteSysUser(Long sysUserId) {
    if (sysUserId == null) {
      return R.error(400, "ID不能为空");
    }
    boolean remove = this.removeById(sysUserId);
    return remove ? R.success("删除成功") : R.error(500, "删除失败");
  }

  public R<String> updateSysUser(SysUser sysUser) {
    if (sysUser == null || sysUser.getId() == null || !StringUtils.hasText(sysUser.getUsername())) {
      return R.error(400, "ID和用户名不能为空");
    }
    // 用户名查重
    LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(SysUser::getUsername, sysUser.getUsername()).ne(SysUser::getId, sysUser.getId());
    if (this.count(wrapper) > 0) {
      return R.error(400, "用户名已存在");
    }
    boolean update = this.updateById(sysUser);
    return update ? R.success("修改成功") : R.error(500, "修改失败");
  }
}
